from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from haystack.query import SearchQuerySet as sqs

from dajax.core import Dajax
from dajaxice.utils import deserialize_form
from goodies.models import Book

@dajaxice_register
def updatecombo(request, option):
    dajax = Dajax()
    options = [['Madrid', 'Barcelona', 'Vitoria', 'Burgos'],
               ['Paris', 'Evreux', 'Le Havre', 'Reims'],
               ['London', 'Birmingham', 'Bristol', 'Cardiff']]
    out = []
    for option in options[int(option)]:
        out.append("<option value='#'>%s</option>" % option)

    dajax.assign('#combo2', 'innerHTML', ''.join(out))
    return dajax.json()



@dajaxice_register
def send_form(request, form):
    dajax = Dajax()
    form =  SearchForm(deserialize_form(form))

    if form.is_valid():
        dajax.remove_css_class('#my_form input', 'error')
        dajax.alert("Form is_valid(), your username is: %s" % form.cleaned_data.get('username'))
    else:
        dajax.remove_css_class('#my_form input', 'error')
        for error in form.errors:
            dajax.add_css_class('#id_%s' % error, 'error')

    return dajax.json()




#@dajaxice_register
#def hello(request,text):#

#    c = [i['author'] for i in sqs().filter(auto_author=text).values('author')]
#    
#    return simplejson.dumps({'completers':c})#

#def update_search(request,form,text_id,text):
#    dajax = Dajax()
#    form = SearchForm(deserialize_form(form))
#    if form.is_valid():
#        dajax.


@dajaxice_register

def basket_add(request,book_id,book_price):
    dajax = Dajax()
    print book_id,book_price,request.session.get('user')

    if not 'basket'  in request.session:
        request.session['basket']     = {}
        request.session['basket_sum'] = int()

    request.session['basket'][book_id] = int(book_price)
    b = request.session['basket'].values()
    request.session['basket_sum'] = sum(b)

    print b




#    if not request.session['basket']['books']: 
#        request.session['basket'] = {}
#        request.session['basket']['books'] = []
#    try: 
#        k = Book.objects.get(pk=book_id) 
#    except: 
#        return None
#    request.session['basket']['books'].append(k)
#    kk = request.session['basket']['books']
#    request.session['basket']['price'] = sum([int(i.price) for i in kk])
#    request.session['basket']['count'] = len(kk)


    dajax.assign('#head_price', 'innerHTML', sum(b))
    dajax.assign('#head_number','innerHTML', len(b))     
    return dajax.json()
        





    